package org.example.lotterysystem.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.lotterysystem.common.utils.JacksonUtil;
import org.example.lotterysystem.dao.dataobject.DeadLetterMessageDO;
import org.example.lotterysystem.dao.mapper.DeadLetterMessageMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/dead-letter")
@Slf4j
public class DeadLetterController {

    @Autowired
    private DeadLetterMessageMapper deadLetterMessageMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/list")
    public List<DeadLetterMessageDO> listPendingMessages() {
        return deadLetterMessageMapper.selectPendingMessages(100);
    }

    @PostMapping("/retry/{id}")
    public String retryMessage(@PathVariable Long id) {
        DeadLetterMessageDO message = deadLetterMessageMapper.selectById(id);
        if (message == null) {
            return "消息不存在";
        }

        try {
            Map<String, String> content = JacksonUtil.readMapValue(message.getMessageContent(),String.class,String.class);

            rabbitTemplate.convertAndSend(
                    message.getExchange(),
                    message.getRoutingKey(),
                    content
            );

            message.setStatus(2); // 处理成功
            message.setRetryCount(message.getRetryCount() + 1);
            message.setLastRetryTime(new Date());
            deadLetterMessageMapper.updateById(message);

            return "重新投递成功";
        } catch (Exception e) {
            log.error("手动重试死信消息失败", e);
            return "重新投递失败: " + e.getMessage();
        }
    }
}